package com.game.server.message;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import com.game.server.db.SqlHelperwrite;
import lombok.Data;
import lombok.extern.log4j.Log4j;

@Data
public abstract class AbstractMessage {

    protected org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass().getName());
    protected final String CharsetName = "UTF-8";

    /*
     * �ַ�תstring
     * 
     * @param buf
     * 
     * @param charsetName
     * 
     * @return
     */
    protected String ReadString(ByteBuffer buf) {
        ByteArrayOutputStream bArray = new ByteArrayOutputStream();
        short len = buf.getShort();
        for (int i = 0; i < len; i++) {
            byte b = buf.get();
            bArray.write(b);
        }
        try {
            return bArray.toString(CharsetName);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        return "";
    }

    protected Long ReadLong(ByteBuffer buf) {
        return buf.getLong();
    }
    
    protected Integer ReadInteger(ByteBuffer buf) {
        return buf.getInt();
    }

    protected Byte ReadByte(ByteBuffer buf) {
        return buf.get();
    }

    protected Short ReadShort(ByteBuffer buf) {
        return buf.getShort();
    }
    
    protected double Readdouble(ByteBuffer buf) {
        return buf.getDouble();
    }
    
    protected float Readfloat(ByteBuffer buf) {
        return buf.getFloat();
    }


    /**
     * string ת�ַ�
     * 
     * @param buf
     * @param value
     * @param charsetName
     */
    protected void WriteString(ByteBuffer buf, String value) {
        if (value == null) {
            buf.putShort((short) 0);
            return;
        }
        byte[] sendBytes = null;
        try {
            sendBytes = value.getBytes(CharsetName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // LogManager.getInstance().Log("str len:"+ sendBytes.length);
        buf.putShort((short) (sendBytes.length));
        for (int i = 0; i < sendBytes.length; i++) {
            // logger.info(sendBytes[i]);
            buf.put(sendBytes[i]);
        }
    }

    protected void WriteInteger(ByteBuffer buf, Integer value) {
        if (value == null) buf.putInt(0);
        else
            buf.putInt(value);
    }

    protected void WriteByte(ByteBuffer buf, Byte value) {
        if (value == null) buf.put((byte) 0);
        else
            buf.put(value);
    }

    protected void WriteLong(ByteBuffer buf, Long value) {
        if (value == null) buf.putLong(0);
        else
            buf.putLong(value);
    }

    protected void WriteShort(ByteBuffer buf, Short value) {
        if (value == null) buf.putShort((short) 0);
        else
            buf.putShort(value);
    }

}